package aiyh.utils.zwl.common;

import aiyh.utils.zwl.common.logging.Logger;
import aiyh.utils.zwl.common.logging.LoggerFactory;
import weaver.conn.ConnStatementDataSource;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.GCONST;
import weaver.general.TimeUtil;
import weaver.general.Util;

import java.io.*;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * 常用工具方法-公用类
 * @author bleach
 * @date 2018-01-18
 * @version 2.0 Modify By Weilin.Zhu 添加日志级别 2018-12-05
 * @version 3.0 Modify By Weilin.Zhu 修改日志输出方式，使用log4j 2020-03-10
 */
public class ToolUtil extends BaseBean {

	Logger logger = LoggerFactory.getLogger("cus");

	/**
	 * 是否开启调试模式
	 */
	boolean isDebug = true;

	/**
	 * 日志层级 （0：调试[Debugger] 1：警告[Warning] 2：错误[Error]
	 */
	private int logLevel = 2;

	private RecordSet rs = new RecordSet();

	/**
	 * 构造方法
	 */
	public ToolUtil() {
		// TODO Auto-generated constructor stub
		logger = LoggerFactory.getLogger("cus");
		//是否开启日志模式
		String isopen = getSystemParamValue("Debug_Mode");

		//输出日志级别
		logLevel = Util.getIntValue(getSystemParamValue("Logger_Level"),-1);

		if("1".equals(isopen)){
			isDebug = true;
		}
	}

	/**
	 * 根据流程类型ID获取其对应的表单名称
	 * @param workflowid 流程类型ID
	 * @return 字符串
	 */
	public String getBillTableNameByWorkflowId(String workflowid){
		String tablename = "";

		if(!"".equals(workflowid)){
			String select_data = "select tablename from workflow_bill where id in (select formid from workflow_base where id = ?)";

			if(rs.executeQuery(select_data, workflowid)){
				if(rs.next()){
					tablename = Util.null2String(rs.getString(1));
				}
			}
		}

		return tablename;
	}

	/**
	 * 查询满足模糊查询的所有标识集合
	 * @param likestr 模糊条件
	 * @return 处理结果
	 */
	public Map<String,String> getSystemParamValueMap(String likestr){
		return getSystemParamList(likestr);
	}

	/**
	 * 查询系统中所有参数配置
	 * @return 参数结果
	 */
	public Map<String,String> getAllSystemParamValue(){
		return getSystemParamList("");
	}


	/**
	 * 获取参数集合
	 * @param likestr 模糊查询的条件
	 * @return 集合
	 */
	private Map<String,String> getSystemParamList(String likestr){
		Map<String,String> param_map = new HashMap<String, String>();

		String select_sql = "select uuid,paramvalue from uf_systemconfig";

		RecordSet rs = new RecordSet();

		if(!"".equals(likestr)){
			select_sql += " where uuid like '%" + likestr + "%'";
		}

		if(rs.execute(select_sql)){
			while(rs.next()){
				String uuid = Util.null2String(rs.getString(1));
				String paramvalue = Util.null2String(rs.getString(2));

				param_map.put(uuid, paramvalue);
			}
		}

		return param_map;

	}

	/**
	 * 获取系统参数设置值
	 * @param uuid 参数标识
	 * @return 返回配置值
	 */
	public String getSystemParamValue(String uuid){
		String paramvalue = "";

		if(!"".equals(uuid)){
			String select_sql = "select paramvalue from uf_systemconfig where uuid = ?";

			RecordSet rs = new RecordSet();
			rs.executeQuery(select_sql,uuid);
			if(rs.next()){
				paramvalue = Util.null2String(rs.getString(1));
			}
		}

		return paramvalue;
	}

	/**
	 * 用数据库值，根据规则转换，获取其最终结果
	 * @param cus_sql 自定义转换的SQL
	 * @param value 参数值
	 * @return 配置值
	 */
	public String getValueByChangeRule(String cus_sql,String value){

		return getValueByChangeRule(cus_sql,value,"");
	}

	/**
	 * 用数据库值，根据规则转换，获取其最终结果
	 * @param cus_sql 自定义转换的SQL
	 * @param value 参数值
	 * @param requestid 流程请求ID
	 * @return 转换后的值
	 */
	public String getValueByChangeRule(String cus_sql,String value,String requestid){

		return getValueByChangeRule(cus_sql,value,requestid,0);
	}

	/**
	 * 用数据库值，根据规则转换，获取其最终结果
	 * @param cus_sql 自定义转换的SQL
	 * @param value 参数值
	 * @param requestid 流程请求ID
	 * @param detailKeyvalue 明细表主键值
	 * @return 值
	 */
	public String getValueByChangeRule(String cus_sql,String value,String requestid,int detailKeyvalue){
		return getValueByChangeRule(cus_sql,value,requestid,detailKeyvalue,null);
	}

	/**
	 * 用数据库值，根据规则转换，获取其最终结果
	 * @param cus_sql 自定义转换的SQL
	 * @param value 参数值
	 * @param requestid 流程请求ID
	 * @param detailKeyvalue 明细表主键值
	 * @param datasourceid 外部数据源ID
	 * @return 处理后的值
	 */
	public String getValueByChangeRule(String cus_sql,String value,String requestid,int detailKeyvalue,String datasourceid){
		String endValue = "";

		cus_sql = cus_sql.replace("&nbsp;", " ");

		cus_sql = cus_sql.replace("{?dt.id}", String.valueOf(detailKeyvalue));

		//参数进行替换
		String sqlString = cus_sql.replace("{?requestid}", requestid);

		sqlString = sqlString.replace("?", value);

		sqlString = ToDBC(sqlString);
		try {
			if(datasourceid != null && !"".equals(datasourceid)){
				ConnStatementDataSource csds = new ConnStatementDataSource(datasourceid);

				csds.setStatementSql(sqlString);

				csds.executeQuery();

				if(csds.next()){
					endValue = Util.null2String(csds.getString(1));
				}

				csds.close();
			}else{

				RecordSet rs = new RecordSet();
				if(rs.executeQuery(sqlString)){
					rs.next();

					endValue = Util.null2String(rs.getString(1));
				}
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return endValue;
	}


	/**
	 * 用数据库值，根据规则转换，获取其最终结果
	 * @param cus_sql 自定义转换的SQL
	 * @param value 参数值
	 * @return 给处理后的值
	 */
	public String getValueByChangeRule_SingleParam(String cus_sql,String value){
		String endValue = "";

		cus_sql = cus_sql.replace("&nbsp;", " ");

		RecordSet rs = new RecordSet();

		if(rs.executeQuery(cus_sql,value)){
			rs.next();

			endValue = Util.null2String(rs.getString(1));
		}

		return endValue;
	}

	/**
	 * 全角转半角
	 * @param input 字符
	 * @return 转换后的字符
	 */
	public String ToDBC(String input) {
		char c[] = input.toCharArray();
		for (int i = 0; i < c.length; i++) {
			if (c[i] == '\u3000') {
				c[i] = ' ';
			} else if (c[i] > '\uFF00' && c[i] < '\uFF5F') {
				c[i] = (char) (c[i] - 65248);
			}
		}
		String returnString = new String(c);
		return returnString;
	}
	/**
	 * 根据字段ID获取其对应的字段名称
	 * @param fieldid 字段id
	 * @return 字段名称
	 */
	public String getFieldNameByFieldid(int fieldid){
		if(fieldid > 0){
			return getFieldNameByFieldid(String.valueOf(fieldid));
		}else{
			return "";
		}
	}

	/**
	 * 根据字段ID获取其对应的字段名称
	 * @param fieldid 字段id
	 * @return 字段名称
	 */
	public String getFieldNameByFieldid(String fieldid){
		String fieldname = "";

		if(!"".equals(fieldid)){

			if(fieldid.startsWith(",")){
				fieldid = fieldid.substring(1);
			}

			if(fieldid.endsWith(",")){
				fieldid =fieldid.substring(0,fieldid.length() - 1);
			}

			String select_sql = "select fieldname from workflow_billfield where id in (" + fieldid + ")";

			RecordSet rs = new RecordSet();

			if(rs.execute(select_sql)){
				while(rs.next()){

					fieldname += "," + Util.null2String(rs.getString(1));
				}
			}
		}

		if(fieldname.startsWith(",")){
			fieldname = fieldname.substring(1);
		}

		return fieldname;
	}

	/**
	 * 输出调试日志
	 * @param logstr 日志信息
	 */
	public void writeDebuggerLog(String logstr){
		if(logLevel >= 0){
			logger.info(logstr);
		}
	}

	/**
	 * 输出调试日志
	 * @param className 类名称
	 * @param logstr 日志信息
	 */
	public void writeDebuggerLog(String className,String logstr){
		if(logLevel >= 0){
			logger.info(logstr);
		}
	}

	/**
	 * 输出警告日志
	 * @param logstr 日志信息
	 */
	public void writeWarningLog(String logstr){
		if(logLevel >= 1){
			logger.warn(logstr);
		}
	}


	/**
	 * 输出警告日志
	 * @param className 类名称
	 * @param logstr 日志信息
	 */
	public void writeWarningLog(String className,String logstr){
		if(logLevel >= 1){
			logger.warn(logstr);
		}
	}

	/**
	 * 输出错误日志
	 * @param logstr 日志信息
	 */
	public void writeErrorLog(String logstr){
		logger.error(logstr);
	}



	/**
	 * 输出错误日志
	 * @param className 类名称
	 * @param logstr 日志信息
	 */
	public void writeErrorLog(String className,String logstr){
		logger.error(logstr);
	}


	/**
	 * 日志输出
	 * @param logstr 日志字符串
	 */
	public void writeDebugLog(Object logstr){
		logger.info(logstr);
	}

	/**
	 * 日志输出
	 * @param logstr 日志字符串
	 * @param o 对象
	 */
	public void writeNewDebuggerLog(Object o,Object logstr){
		logger.info(logstr);
	}

	/**
	 * 写入同步的日志文件
	 * @param o 日志字符串
	 * @param  s 日志字符串
	 * @deprecated 该写入文件的日志输出方式删除
	 */
	protected void writeNewLog(String o,String s){
		try {
			String filename = "cus_" + TimeUtil.getCurrentDateString() + "_ecology.log";


			String folder = GCONST.getRootPath() + "log" + File.separatorChar + "cus";

			//this.writeDebugLog("folder:[" + folder + "]");

			File f = new File(folder);

			// 创建文件夹
			if (!f.exists()) {
				f.mkdirs();
			}

			f = new File(folder + File.separatorChar  + filename);
			//文件不存在，则直接创建
			if(!f.exists()){
				f.createNewFile();
			}

			BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f, true)));

			out.write("[" + o + "][" + TimeUtil.getCurrentTimeString() + "]:"+ s + "\r\n");

			//关闭写入流
			out.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			writeDebugLog("创建日志文件存在异常:[" + e.getMessage() + "/" + e.toString() + "]");
		}
	}

	/**
	 * 根据建模模块ID获取其对应的表单名称
	 * @param modeid 模块ID
	 * @return 建模表单名称
	 */
	public String getTableNameByModeID(int modeid){
		String modeTableName = "";

		if(modeid > 0){
			String select_sql = "select tablename from modeinfo m left join workflow_bill wb on m.formid = wb.id " +
					"left join ModeFormExtend me on me.formid = wb.id where m.id = ?";

			RecordSet rs = new RecordSet();

			if(rs.executeQuery(select_sql,modeid)){
				if(rs.next()){
					modeTableName = Util.null2String(rs.getString(1));
				}
			}
		}

		return modeTableName;
	}

	/**
	 * 根据流程请求ID获取其对应的表单名称
	 * @param requestid 流程请求id
	 * @return 获取表名
	 */
	public String getTableNameByRequestID(int requestid) {
		String billTableName = "";
		if(requestid > 0) {
			String select_sql = "select wbi.tablename from workflow_requestbase wr inner join workflow_base wb on wr.workflowid = wb.id "
					+ "inner join workflow_bill wbi on wbi.id = wb.formid where wr.requestid = ?";

			RecordSet rs = new RecordSet();

			if(rs.executeQuery(select_sql,requestid)){
				if(rs.next()){
					billTableName = Util.null2String(rs.getString(1));
				}
			}

		}
		return billTableName;
	}

	/**
	 * @return the isDebug
	 */
	public boolean isDebug() {
		return isDebug;
	}
}
